package SocketLearn.NetSocketLearn;



import org.junit.jupiter.api.Test;

import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author Lenl
 * @version v1.0
 * @create 2021-06-06 15:18
 * @description
 *
 * 客户端发送文件到服务端，接收后返回信息表示已接收，客户端接收该信息
 *
 */
public class TCPTest3 {
    @Test
    public void client(){
        Socket socket=null;
        OutputStream os=null;
        FileInputStream fis=null;
        try {
            String path="C:\\Users\\Lenl\\OneDrive\\图片\\Saved Pictures\\壁纸\\chuyin.jpg";
            socket=new Socket(InetAddress.getByName("127.0.0.1"),9900);
            os=socket.getOutputStream();
            fis=new FileInputStream(new File(path));
            byte[] buffer=new byte[1024];
            int len;
            while((len=fis.read(buffer))!=-1){
                os.write(buffer,0,len);
            }
            System.out.println("发送完成");
            socket.shutdownOutput();//关闭输出操作

            //接收来自服务端的数据，并显示在控制台
            InputStream is= socket.getInputStream();
            ByteArrayOutputStream baos=new ByteArrayOutputStream();
            byte[] buffer2=new byte[1024];
            int len2;
            while((len2=is.read(buffer2))!=-1){
                baos.write(buffer2,0,len2);
            }
            System.out.println(baos.toString());

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(socket!=null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(os!=null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(fis!=null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    @Test
    public void server() throws IOException {
        String path="D:\\Java Learn\\IOLearnTestFile\\picturetest\\chuyin.jpg";
        ServerSocket ss=new ServerSocket(9900);
        Socket s=ss.accept();
        InputStream is=s.getInputStream();

        FileOutputStream fos=new FileOutputStream(new File(path));
        byte[] buffer=new  byte[1024];
        int len;
        while((len=is.read(buffer))!=-1){
            fos.write(buffer,0,len);
        }
        System.out.println("接收完成！");

        //服务端给与客户端反馈
        OutputStream os=s.getOutputStream();
        os.write("你好，文件已接收！请核实。".getBytes());


        ss.close();;
        s.close();;
        os.close();
        fos.close();
    }
}
